package com.lyy.common.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyy.common.utils.DateUtils;
import com.lyy.common.utils.SpringUtil;
import com.lyy.system.dao.SysTaskDao;
import com.lyy.system.pojo.SysTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @program: apip_tools
 * @description: 定时任务配置
 * @author: YW
 * @create: 2021-02-02 10:55
 **/
@Lazy(value = false)
@Component
@Slf4j
public class SysTaskConfig implements SchedulingConfigurer {
    @Resource
    private SysTaskDao sysTaskDao;

    //从数据库里取得所有要执行的定时任务
    private List<SysTask> getAllTasks() {
        QueryWrapper<SysTask> sysTaskQueryWrapper = new QueryWrapper<>();
        sysTaskQueryWrapper.eq("del_flag", "0");
        return sysTaskDao.selectList(sysTaskQueryWrapper);
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        List<SysTask> taskList = getAllTasks();
        log.info("定时任务启动,预计启动任务数量：{},时间：{}", taskList.size(), DateUtils.formatDateTime(new Date()));
        //通过校验的数据执行定时任务
        int count = 0;
        if (taskList.size() > 0) {
            for (SysTask sysTask : taskList) {
                try {
                    scheduledTaskRegistrar.addTriggerTask(getRunnable(sysTask), getTrigger(sysTask));
                    count++;
                } catch (Exception e) {
                    log.info("定时任务启动错误类名：{},任务名称：{},错误信息：{}", sysTask.getClassName(), sysTask.getMethodName(), e.getMessage());
                }
            }
        }
        log.info("定时任务实际启动数量：{},时间：{}", count, DateUtils.formatDateTime(new Date()));
    }

    private Runnable getRunnable(SysTask sysTask) {
        return new Runnable() {
            @Override
            public void run() {
                try {
                    Object obj = SpringUtil.getBean(sysTask.getClassName());
                    Method method = obj.getClass().getMethod(sysTask.getMethodName());
                    method.invoke(obj);
                } catch (InvocationTargetException e) {
                    log.info("定时任务启动错误，反射异常-类名：{},方法名：{},错误信息：{}", sysTask.getClassName(), sysTask.getMethodName(), e.getMessage());
                } catch (Exception e) {
                    log.info("错误信息：{}", e.getMessage());
                }
            }
        };
    }

    private Trigger getTrigger(SysTask sysTask) {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //将Cron 0/1 * * * * ? 输入取得下一次执行的时间
                CronTrigger trigger = new CronTrigger(sysTask.getTaskCron());
                return trigger.nextExecutionTime(triggerContext);
            }
        };
    }

    private List<SysTask> checkDataList(List<SysTask> list) {
        StringBuilder errMsg = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (!"success".equalsIgnoreCase(checkOneData(list.get(i)))) {
                errMsg.append(list.get(i).getTaskName()).append(";");
                list.remove(list.get(i));
                i--;
            }
        }
        if (StringUtils.isNotEmpty(errMsg.toString())) {
            errMsg.insert(0, "未启动的任务:");
            log.info("错误信息：{}", errMsg.toString());
        }
        return list;
    }

    private String checkOneData(SysTask task) {
        String result = "success";
        Class clazz = null;
        try {
            clazz = Class.forName(task.getClassName());
            Object obj = SpringUtil.getBean(clazz);
            Method method = obj.getClass().getMethod(task.getMethodName());
            String cron = task.getTaskCron();
            if (StringUtils.isBlank(cron)) {
                result = "定时任务启动错误，无cron:" + task.getTaskName();
                log.info("错误结果：{}", result);
            }
        } catch (ClassNotFoundException e) {
            result = "定时任务启动错误，找不到类:" + task.getClassName() + e.getMessage();
            log.info("错误信息：{}", result);
        } catch (NoSuchMethodException e) {
            result = "定时任务启动错误，找不到方法,方法必须是public:" + task.getClassName() + ";" + task.getMethodName() + ";" + e.getMessage();
            log.info("错误信息：{}", result);
        } catch (Exception e) {
            log.info("错误信息：{}", e.getMessage());
        }
        return result;
    }

}
